package com.vince.file;
import com.vince.staticdata.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *  生成随机验证码
 *  明白http请求消息的数据部分--
 *   upload组件的工作流程
 *      浏览器上传下载
 *    
 * @author susp
 *
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    String message=null;
		String savepath=this.getServletContext().getRealPath("/WEB-INF/upload");
		File file=new File(savepath);
		if(!file.exists()&&!file.isDirectory()){
			file.mkdir();
		}
		
		//使用appach文件上传组件上传文件的步骤
		//1,创建一个DiskFileItemFactory工厂
		DiskFileItemFactory factory=new DiskFileItemFactory();
		//2.创建一个文件上传解析器
		ServletFileUpload upload=new ServletFileUpload(factory);
		//解决上传文件名的中文乱码
		upload.setHeaderEncoding("utf-8");
		//3，判断提交上来的数据是否是上传表单的数据
		if(!ServletFileUpload.isMultipartContent(request)){
			//按照传统方式获取数据
			return;
			
		}
		//4，使用ServletFileUpload解析器解析上传书局，解析结果返回的是一个List<FileItem>集合。
		List<FileItem> fl=null;
		try {
			fl=upload.parseRequest(request);
			for(FileItem item:fl){
				//如果fileitem中封装的是普通的输入项数据
				if(item.isFormField()){
					String name=item.getFieldName();
					//解决普通输入项的中文乱码问题
					String value=item.getString("utf-8");
					System.out.println(name+"="+value);
					
				}else{
					//如果fileitem中封装的是上传文件
					String filename=item.getName();
					System.out.println(filename);
					if(filename==null||filename.trim().equals("")){
						continue;
					}
					//处理获取到的上传文件的文件名对的路径部分，只保留文件名
					filename=filename.substring(filename.lastIndexOf("\\")+1);
					
					//获取item的上传文件的输入流 
					InputStream in=item.getInputStream();
					//创建一个文件输出流
					FileOutputStream out=new FileOutputStream(savepath + "\\" + filename);
					//创建一个缓冲区
					byte[] buffer=new byte[1024];
					int len=-1;
					while((len=in.read(buffer))!=-1){
						out.write(buffer, 0, len);
					}
					in.close();
					out.close();
					//删除上传文件时生成的临时文件
					item.delete();
					message="上传文件成功";
				}
			}
			}catch (FileUploadException e) {
				message="上传文件失败";
			e.printStackTrace();
		}
//		request.setAttribute("message", message);
//		request.getRequestDispatcher("/view/file/message.jsp").forward(request, response);
		response.sendRedirect(request.getContextPath()+"/view/file/message.jsp?message="+message);//?message=message
	}
}
